package org.administer.realms;

import org.administer.dao.CrmCustomerDao;
import org.administer.dao.CrmPermissionDao;
import org.administer.dao.CrmUserDao;
import org.administer.pojo.CrmCustomers;
import org.administer.pojo.CrmPermission;
import org.administer.pojo.CrmUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    private CrmUserDao crmUserDao;
    private CrmPermissionDao crmPermissionDao;

    public void setCrmUserDao(CrmUserDao crmUserDao) {
        this.crmUserDao = crmUserDao;
    }

    public void setCrmPermissionDao(CrmPermissionDao crmPermissionDao) {
        this.crmPermissionDao = crmPermissionDao;
    }

    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("ni lai 授权验证了！");
        CrmUser sysUser = (CrmUser)principalCollection.getPrimaryPrincipal();
        List<CrmPermission> list = crmPermissionDao.getPersByUserId(sysUser.getId());
        Set<String> set = new HashSet<>();
        for (CrmPermission per :
                list) {
            set.add(per.getPercode());
            System.out.println(per.getPercode());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    /**
     * 用户认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal= (String) token.getPrincipal();
        CrmUser crmUser=crmUserDao.login(principal);
//        System.out.println(crmUser);
        if (crmUser==null){
            return null;
        }else if(crmUser.getAvailable()==null){
            throw  new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(crmUser,crmUser.getPassword(), ByteSource.Util.bytes(crmUser.getSalt()),"heha");
    }
}
